package vip.denglei.company.service.app.impl;

import cn.binarywang.wx.miniapp.api.WxMaExpressService;
import cn.binarywang.wx.miniapp.api.WxMaOrderShippingService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.express.WxMaExpressDelivery;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.*;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaOrderShippingInfoBaseResponse;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaShopDeliveryGetCompanyListResponse;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.response.SubscribeResp;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.denglei.company.mapper.AppUserOrderMapper;
import vip.denglei.company.mapper.WorkWechatMsgContextMapper;
import vip.denglei.company.mapper.WorkWechatMsgInfoMapper;
import vip.denglei.company.model.app.*;
import vip.denglei.company.model.app.bo.AppUserOrderBO;
import vip.denglei.company.model.app.bo.BindingLogisticsBO;
import vip.denglei.company.model.app.query.AppUserOrderQuery;
import vip.denglei.company.model.app.vo.AppUserOrderSaveVO;
import vip.denglei.company.model.app.vo.QueryAppUserOrderPageVO;
import vip.denglei.company.model.app.vo.QueryUserOrderDetailsByOrderIdVO;
import vip.denglei.company.model.app.vo.UserOrderDetailsVO;
import vip.denglei.company.service.app.*;
import vip.denglei.company.util.HttpResult;
import vip.denglei.company.util.WorkWechatSendMsgUtils;
import vip.denglei.company.util.kuidi100.KdUtil;
import vip.denglei.company.util.kuidi100.SubscribePushParamResp;

import javax.annotation.Resource;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AppUserOrderServiceImpl extends ServiceImpl<AppUserOrderMapper, AppUserOrder> implements AppUserOrderService {
    @Resource
    private AppUserOrderMapper appUserOrderMapper;
    @Resource
    private AppUserOrderDetailsService appUserOrderDetailsService;
    @Resource
    private AppShoppingCartService shoppingCartService;
    @Resource
    private ExpressDeliveryRecordService expressDeliveryRecordService;

    @Resource
    private ExpressCompanyService expressCompanyService;
    @Resource
    private AppProductService appProductService;
    @Autowired
    public WorkWechatMsgContextMapper workWechatMsgContextMapper;
    @Autowired
    public WorkWechatMsgInfoMapper workWechatMsgInfoMapper;
    @Resource
    public AppUserOrderDetailsService applicationUserOrderDetailsService;

    @Resource
    private AppUserService appUserService;

    @Resource
    private WxMaService wxMaService;


    @Override
    @Transactional
    public HttpResult saveUserOrder(AppUserOrderBO appUserOrderBO) {
        //判断库存
        //库存状态
        AtomicReference<Boolean> inventoryStatus = new AtomicReference<>(Boolean.TRUE);
        LambdaQueryWrapper<AppProduct> appProductLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appProductLambdaQueryWrapper.in(AppProduct::getProId, appUserOrderBO.getOrderDetailsList().stream().map(AppUserOrderDetails::getProId).collect(Collectors.toList()));
        List<AppProduct> appProductList = appProductService.list(appProductLambdaQueryWrapper);
        appProductList.stream().forEach(appProduct -> {
            Optional<AppUserOrderDetails> appProductOptional = appUserOrderBO.getOrderDetailsList().stream().filter(appUserOrderDetails -> Objects.equal(appUserOrderDetails.getProId(), appProduct.getProId())).findFirst();
            if (appProductOptional.isPresent()) {
                if (appProduct.getProCount() <= appProductOptional.get().getProVolume()) {

                    inventoryStatus.set(Boolean.FALSE);
                }

            }
        });
        if (inventoryStatus.get().equals(Boolean.FALSE)) {
            return HttpResult.err(800, "商品库存不足");
        }
        AppUserOrderSaveVO appUserOrderSaveVO = new AppUserOrderSaveVO();
        appUserOrderSaveVO.setOrderId(String.valueOf(IdUtil.getSnowflakeNextId()));
        AppUserOrder appUserOrder = new AppUserOrder();
        //保存订单
        appUserOrder.setOrderId(appUserOrderSaveVO.getOrderId());
        appUserOrder.setOrderNote(appUserOrderBO.getOrderNote());
        appUserOrder.setOrderStatus(0);
        appUserOrder.setUserId(appUserOrderBO.getUserId());
        appUserOrder.setFreight(appUserOrderBO.getFreight());
        appUserOrder.setDeleteFlag(0);
        appUserOrder.setPaymentStatus(0);
        appUserOrder.setLogisticsStatus(1);
        appUserOrder.setProAmount(appUserOrderBO.getProAmount());
        appUserOrder.setProTotal(appUserOrderBO.getProTotal());
        appUserOrder.setAddName(appUserOrderBO.getAddName());
        appUserOrder.setAddPhone(appUserOrderBO.getAddPhone());
        appUserOrder.setProvince(appUserOrderBO.getProvince());
        appUserOrder.setCity(appUserOrderBO.getCity());
        appUserOrder.setCounty(appUserOrderBO.getCounty());
        appUserOrder.setAddInfo(appUserOrderBO.getAddInfo());
        appUserOrder.setCompanyName(appUserOrderBO.getCompanyName());

        //保存订单详情
        List<Integer> shoppingCartIdLists = Lists.newArrayList();
        AtomicReference<Integer> totalProVolume = new AtomicReference<>(0);
        appUserOrderBO.getOrderDetailsList().stream().forEach(appUserOrderDetails -> {
            //替换图片
            Optional<AppProduct> appProductOptional = appProductList.stream().filter(p -> appUserOrderDetails.getProId().equals(p.getProId())).findFirst();
            if (appProductOptional.isPresent()) {
                appUserOrderDetails.setProImg(appProductOptional.get().getProImg());
            }
            if (!Objects.equal(appUserOrderDetails.getShoppingCartId(), null)) {
                shoppingCartIdLists.add(appUserOrderDetails.getShoppingCartId());
            }
            appUserOrderDetails.setOrderId(appUserOrderSaveVO.getOrderId());
            totalProVolume.updateAndGet(v -> v + totalProVolume.get() + appUserOrderDetails.getProVolume());
        });
        appUserOrder.setProVolume(totalProVolume.get());

        this.save(appUserOrder);
        appUserOrderDetailsService.saveBatch(appUserOrderBO.getOrderDetailsList());
        //删除购物车信息
        if (shoppingCartIdLists.size() > 0) {
            shoppingCartService.removeByIds(shoppingCartIdLists);
        }
        return HttpResult.success(appUserOrderSaveVO);

    }

    @Override
    public HttpResult queryUserOrderPage(AppUserOrderQuery appUserOrderQuery) {
        Page<AppUserOrder> queryAppUserOrderPageVOPage = new Page<>(appUserOrderQuery.getPageNum(), appUserOrderQuery.getPageSize());
        List<QueryAppUserOrderPageVO> queryAppUserOrderVOList = Lists.newArrayList();
        IPage<QueryAppUserOrderPageVO> queryAppUserOrderPageVOIPage = new Page<>();
        LambdaQueryWrapper<AppUserOrder> appUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getUserId, appUserOrderQuery.getUserId());
        appUserOrderLambdaQueryWrapper.orderByDesc(AppUserOrder::getCreateTime);
        if (Objects.equal(appUserOrderQuery.getOrderStatus(), 0)) {
            //待付款
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getPaymentStatus, 0);
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getLogisticsStatus, 1);

        } else if (Objects.equal(appUserOrderQuery.getOrderStatus(), 1)) {
            //待发货
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getPaymentStatus, 1);
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getLogisticsStatus, 1);

        } else if (Objects.equal(appUserOrderQuery.getOrderStatus(), 2)) {
            //待收货
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getPaymentStatus, 1);
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getLogisticsStatus, 2);

        } else if (Objects.equal(appUserOrderQuery.getOrderStatus(), 3)) {
            //已完成
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getPaymentStatus, 1);
            appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getLogisticsStatus, 3);
        }

        IPage<AppUserOrder> appUserOrderIPage = this.page(queryAppUserOrderPageVOPage, appUserOrderLambdaQueryWrapper);
        queryAppUserOrderPageVOIPage.setSize(appUserOrderIPage.getSize());
        queryAppUserOrderPageVOIPage.setCurrent(appUserOrderIPage.getCurrent());
        queryAppUserOrderPageVOIPage.setTotal(appUserOrderIPage.getTotal());
        queryAppUserOrderPageVOIPage.setPages(appUserOrderIPage.getPages());
        if (!appUserOrderIPage.getRecords().isEmpty()) {

            //查询订单详情
            LambdaQueryWrapper<AppUserOrderDetails> appUserOrderDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appUserOrderDetailsLambdaQueryWrapper.in(AppUserOrderDetails::getOrderId, appUserOrderIPage.getRecords().stream().map(AppUserOrder::getOrderId).collect(Collectors.toList()));
            List<AppUserOrderDetails> userOrderDetailsList = appUserOrderDetailsService.list(appUserOrderDetailsLambdaQueryWrapper);
            List<String> proImgList = userOrderDetailsList.stream().map(AppUserOrderDetails::getProImg).collect(Collectors.toList());
            appUserOrderIPage.getRecords().forEach(appUserOrder -> {
                QueryAppUserOrderPageVO queryAppUserOrderVO = new QueryAppUserOrderPageVO();
                queryAppUserOrderVO.setOrderId(appUserOrder.getOrderId());
                queryAppUserOrderVO.setCreateTime(appUserOrder.getCreateTime());
                queryAppUserOrderVO.setOrderStatus(appUserOrder.getOrderStatus());
                queryAppUserOrderVO.setProTotal(appUserOrder.getProTotal());
                queryAppUserOrderVO.setProImgList(proImgList);
                queryAppUserOrderVO.setAppUserOrderDetailsList(userOrderDetailsList.stream().filter(s -> s.getOrderId().equals(appUserOrder.getOrderId())).collect(Collectors.toList()));
                queryAppUserOrderVOList.add(queryAppUserOrderVO);
            });
            queryAppUserOrderPageVOIPage.setRecords(queryAppUserOrderVOList);

        }

        return HttpResult.success(queryAppUserOrderPageVOIPage);
    }

    @Override
    public HttpResult queryUserOrderDetailsByOrderId(String orderId) {
        QueryUserOrderDetailsByOrderIdVO queryUserOrderDetailsByOrderIdVO = new QueryUserOrderDetailsByOrderIdVO();
        LambdaQueryWrapper<AppUserOrder> appUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getOrderId, orderId);
        AppUserOrder appUserOrder = this.getOne(appUserOrderLambdaQueryWrapper);
        if (java.util.Objects.nonNull(appUserOrder)) {
            UserOrderDetailsVO userOrderDetailsVO = new UserOrderDetailsVO();
            BeanUtil.copyProperties(appUserOrder, userOrderDetailsVO);
            userOrderDetailsVO.setCom(appUserOrder.getCom());
            userOrderDetailsVO.setNu(appUserOrder.getNum());
            userOrderDetailsVO.setLogisticsStatus(appUserOrder.getLogisticsStatus());
            queryUserOrderDetailsByOrderIdVO.setUserOrderDetailsVO(userOrderDetailsVO);
            //商品详情
            LambdaQueryWrapper<AppUserOrderDetails> appUserOrderDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appUserOrderDetailsLambdaQueryWrapper.eq(AppUserOrderDetails::getOrderId, orderId);
            queryUserOrderDetailsByOrderIdVO.setAppUserOrderDetailsList(appUserOrderDetailsService.list(appUserOrderDetailsLambdaQueryWrapper));


//            //查询物流信息
//            QueryTrackResp queryTrackResp = null;
//            try {
//                if (!appUserOrder.getLogisticsStatus().equals(3)) {
//                    if (StrUtil.isNotEmpty(appUserOrder.getCom()) && StrUtil.isNotEmpty(appUserOrder.getNum())) {
//                        queryTrackResp = KdUtil.queryTrack(appUserOrder.getCom(), appUserOrder.getNum(), null);
//                        if (queryTrackResp.getStatus().equals("200")) {
//                            appUserOrder.setLogisticsStatus(Integer.valueOf(queryTrackResp.getState()));
//                            if (CollectionUtil.isNotEmpty(queryTrackResp.getData())) {
//                                //添加物流保存信息
//                                List<ExpressDeliveryRecord> expressDeliveryRecordList = new ArrayList<>();
//                                queryTrackResp.getData().stream().forEach(queryTrackData -> {
//                                    ExpressDeliveryRecord expressDeliveryRecord = new ExpressDeliveryRecord();
//                                    expressDeliveryRecord.setOrderId(appUserOrder.getOrderId());
//                                    expressDeliveryRecord.setFtime(DateUtil.parse(queryTrackData.getFtime()));
//                                    expressDeliveryRecord.setContext(queryTrackData.getContext());
//                                    expressDeliveryRecordList.add(expressDeliveryRecord);
//                                });
//                                //保存快递信息，并去重
//                                LambdaQueryWrapper<ExpressDeliveryRecord> expressDeliveryRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                                expressDeliveryRecordLambdaQueryWrapper.eq(ExpressDeliveryRecord::getOrderId, appUserOrder.getOrderId());
//                                expressDeliveryRecordService.remove(expressDeliveryRecordLambdaQueryWrapper);
//                                expressDeliveryRecordService.saveBatch(expressDeliveryRecordList);
//                                appUserOrder.setDeliveryTime(expressDeliveryRecordList.stream().map(ExpressDeliveryRecord::getFtime).min(Date::compareTo).get());
//                                if (queryTrackResp.getState().equals("3") || queryTrackResp.getState().equals("6")) {
//                                    appUserOrder.setOrderStatus(3);
//                                }
//
//                                this.updateById(appUserOrder);
//                            }
//
//                        }
//                    }
//                }
//
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
            LambdaQueryWrapper<ExpressDeliveryRecord> expressDeliveryRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            expressDeliveryRecordLambdaQueryWrapper.eq(ExpressDeliveryRecord::getOrderId, orderId);
            List<ExpressDeliveryRecord> expressDeliveryRecordList = expressDeliveryRecordService.list(expressDeliveryRecordLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(expressDeliveryRecordList)) {
                Collections.sort(expressDeliveryRecordList, Comparator.comparing(ExpressDeliveryRecord::getFtime).reversed());
                queryUserOrderDetailsByOrderIdVO.setAppLogisticsInfoVOList(expressDeliveryRecordList);
            }


        }

        return HttpResult.success(queryUserOrderDetailsByOrderIdVO);
    }

    @Override
    public HttpResult bindingLogistics(BindingLogisticsBO bindingLogisticsBO) {
        //判断快递单号是否被重复绑定
        LambdaQueryWrapper<AppUserOrder> bindingappUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bindingappUserOrderLambdaQueryWrapper.eq(AppUserOrder::getNum, bindingLogisticsBO.getNu());
        if (this.count(bindingappUserOrderLambdaQueryWrapper) > 0) {
            return HttpResult.err("该单号已被使用");
        }
        //查询订单物流状态是否为已签收，值来源快递单当前状态，默认为0在途，1揽收，2疑难，3签收，4退签，5派件，8清关，14拒签等10个基础物流状态，
        LambdaQueryWrapper<AppUserOrder> appUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appUserOrderLambdaQueryWrapper.in(AppUserOrder::getOrderId, bindingLogisticsBO.getOrderIdList());
        List<AppUserOrder> appUserOrderList = this.list(appUserOrderLambdaQueryWrapper);
        if (!appUserOrderList.isEmpty()) {
            List<AppUserOrder> bindingLogisticsList = appUserOrderList.stream().filter(a -> StrUtil.isEmpty(a.getCom())).collect(Collectors.toList());
            if (!bindingLogisticsList.isEmpty()) {
                LambdaQueryWrapper<ExpressCompany> companyLambdaQueryWrapper = new LambdaQueryWrapper<>();
                companyLambdaQueryWrapper.eq(ExpressCompany::getCom, bindingLogisticsBO.getCom());
                ExpressCompany expressCompany = expressCompanyService.getOne(companyLambdaQueryWrapper);
                if (java.util.Objects.nonNull(expressCompany)) {
                    bindingLogisticsList.stream().forEach(appUserOrder -> {
                        appUserOrder.setCom(expressCompany.getComName());
                        appUserOrder.setNum(bindingLogisticsBO.getNu());
                        appUserOrder.setDeliveryTime(DateUtil.date());
                    });
                }
                //订阅推送快递单号信息
                try {
                    SubscribeResp subscribeReq = KdUtil.subscribe(bindingLogisticsBO.getCom(), bindingLogisticsBO.getNu(), bindingLogisticsList.get(0).getAddPhone(), "https://hbcaiyu.cn/company/appUserOrder/logisticsNotify");
                    if ("200".equals(subscribeReq.getReturnCode())) {
                        bindingLogisticsList.stream().forEach(appUserOrder -> {
                            List<ShippingListBean> shippingList = Lists.newArrayList();
                            ShippingListBean shippingListBean = new ShippingListBean();
                            ContactBean contactBean = new ContactBean();
                            contactBean.setReceiverContact(StrUtil.hide(appUserOrder.getAddPhone(), 3, 3));
                            shippingListBean.setContact(contactBean);
                            LambdaQueryWrapper<AppUserOrderDetails> appUserOrderDetailsLambdaQueryWrappera = new LambdaQueryWrapper();
                            appUserOrderDetailsLambdaQueryWrappera.eq(AppUserOrderDetails::getOrderId, appUserOrder.getOrderId());
                            List<AppUserOrderDetails> appUserOrderDetailsList = applicationUserOrderDetailsService.list(appUserOrderDetailsLambdaQueryWrappera);
                            if (appUserOrder.getPushStatus().equals(1)) {
                                String concatenatedDetails = appUserOrderDetailsList.stream()
                                        .map(orderDetails -> {
                                            return "  #### 商品名称：" + orderDetails.getProName() + " ,数量：`" + orderDetails.getProVolume() + orderDetails.getProUnit() + "`,单价：" + orderDetails.getProPrice() / 100 + "元\\n";
                                        }).collect(Collectors.joining(""));
                                WorkWechatSendMsgUtils.setBotMsg("# 发货通知\\n订单编号：" + appUserOrder.getOrderId() + "\\n物流公司`：" + appUserOrder.getCom() + "`\\n物流单号：`" + appUserOrder.getNum() + "`\\n订单总金额：`" + appUserOrder.getProTotal() / 100 + "`元\\n订单时间：" + DateUtil.formatDateTime(appUserOrder.getCreateTime()) + "\\n" +
                                        "## 发货地址信息 \\n#### 收货人名称：" + appUserOrder.getAddName() + ",\\n #### 收货人电话：" + appUserOrder.getAddPhone() + ",\\n#### 收货人地址：" +
                                        appUserOrder.getProvince() + appUserOrder.getCity() + appUserOrder.getCounty() + appUserOrder.getAddInfo() + appUserOrder.getCompanyName() +
                                        "\\n> ## 发货商品信息\\n>" +
                                        concatenatedDetails +
                                        "`请关注快递信息动态`", "markdown", 1, 5, workWechatMsgInfoMapper, workWechatMsgContextMapper);
                                appUserOrder.setPushStatus(2);
                            }
                            //设置为发货信息
                            appUserOrder.setOrderStatus(2);
                            appUserOrder.setLogisticsStatus(2);
                            //推送小程序发货平台;
                            WxMaOrderShippingInfoUploadRequest wxMaOrderShippingInfoUploadRequest = new WxMaOrderShippingInfoUploadRequest();
                            OrderKeyBean orderKeyBean = new OrderKeyBean();
                            orderKeyBean.setMchId("1647484305");
                            orderKeyBean.setOrderNumberType(1);
                            orderKeyBean.setOutTradeNo(appUserOrder.getOutTradeNo());
                            wxMaOrderShippingInfoUploadRequest.setOrderKey(orderKeyBean);
                            wxMaOrderShippingInfoUploadRequest.setLogisticsType(1);
                            wxMaOrderShippingInfoUploadRequest.setDeliveryMode(1);
                            ZonedDateTime now = ZonedDateTime.now();
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
                            String formatted = now.format(formatter);
                            wxMaOrderShippingInfoUploadRequest.setUploadTime(formatted);
                            PayerBean payerBean = new PayerBean();
                            LambdaQueryWrapper<AppUserInfo> appUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            appUserLambdaQueryWrapper.eq(AppUserInfo::getUserId, appUserOrder.getUserId());
                            AppUserInfo appUserInfo = appUserService.getOne(appUserLambdaQueryWrapper);
                            payerBean.setOpenid(appUserInfo.getWechatId());
                            wxMaOrderShippingInfoUploadRequest.setPayer(payerBean);
                            String itemDesc = appUserOrderDetailsList.stream()
                                    .map(orderDetails -> {
                                        return "商品名称：" + orderDetails.getProName() + ",数量" + orderDetails.getProVolume() + orderDetails.getProUnit() + ",单价：" + orderDetails.getProPrice() / 100 + "元\\n";
                                    }).collect(Collectors.joining(""));
                            if (itemDesc.length() > 120) {
                                shippingListBean.setItemDesc(itemDesc.substring(0, 118));
                            } else {
                                shippingListBean.setItemDesc(itemDesc);
                            }
                            try {
                                List<WxMaExpressDelivery> expressDeliveryList = wxMaService.getExpressService().getAllDelivery();
                                if (!expressDeliveryList.isEmpty()) {
                                    Optional<WxMaExpressDelivery> companyListBean = expressDeliveryList.stream().filter(s -> s.getDeliveryName().equals(appUserOrder.getCom())).findFirst();
                                    if (companyListBean.isPresent()) {
                                        shippingListBean.setExpressCompany(companyListBean.get().getDeliveryId());
                                    }
                                }
                            } catch (WxErrorException e) {
                                throw new RuntimeException(e);
                            }
                            shippingListBean.setTrackingNo(bindingLogisticsBO.getNu());
                            shippingList.add(shippingListBean);
                            wxMaOrderShippingInfoUploadRequest.setShippingList(shippingList);
                            try {
                                WxMaOrderShippingInfoBaseResponse wxMaOrderShippingInfoBaseResponse = wxMaService.getWxMaOrderShippingService().upload(wxMaOrderShippingInfoUploadRequest);
                                appUserOrder.setSyncStatus(1);
                                log.info("小程序发货:wxMaOrderShippingInfoBaseResponse{}", wxMaOrderShippingInfoBaseResponse);
                                log.info("同步成功");
                            } catch (WxErrorException e) {
                                throw new RuntimeException(e);
                            }
                        });

                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                this.updateBatchById(bindingLogisticsList);
            }
        }
        return HttpResult.success();
    }

    @Override
    public void modifyInventory(String orderId) {
        LambdaQueryWrapper<AppUserOrderDetails> appUserOrderDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appUserOrderDetailsLambdaQueryWrapper.eq(AppUserOrderDetails::getOrderId, orderId);
        List<AppUserOrderDetails> appUserOrderDetailsList = appUserOrderDetailsService.list(appUserOrderDetailsLambdaQueryWrapper);
        if (ObjectUtil.isNotEmpty(appUserOrderDetailsList)) {
            appProductService.modifyInventory(appUserOrderDetailsList);
        }

    }

    @Override
    public SubscribeResp LogisticsNotify(SubscribePushParamResp subscribePushParamResp) {
        SubscribeResp subscribeResp = new SubscribeResp();
        subscribeResp.setResult(Boolean.FALSE);
        log.info("LogisticsNotify   参数 subscribePushParamResp:{}", subscribePushParamResp);
        LambdaQueryWrapper<AppUserOrder> appUserOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appUserOrderLambdaQueryWrapper.eq(AppUserOrder::getNum, subscribePushParamResp.getLastResult().getNu());
        List<AppUserOrder> appUserOrderList = this.list(appUserOrderLambdaQueryWrapper);
        if (!appUserOrderList.isEmpty()) {
            //添加物流保存信息
            appUserOrderList.stream().forEach(appUserOrder -> {
                List<ExpressDeliveryRecord> expressDeliveryRecordList = new ArrayList<>();
                subscribePushParamResp.getLastResult().getData().stream().forEach(queryTrackData -> {
                    ExpressDeliveryRecord expressDeliveryRecord = new ExpressDeliveryRecord();
                    expressDeliveryRecord.setOrderId(appUserOrder.getOrderId());
                    expressDeliveryRecord.setFtime(DateUtil.parse(queryTrackData.getFtime()));
                    expressDeliveryRecord.setContext(queryTrackData.getContext());
                    expressDeliveryRecordList.add(expressDeliveryRecord);
                });
                //保存快递信息，并去重
                LambdaQueryWrapper<ExpressDeliveryRecord> expressDeliveryRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                expressDeliveryRecordLambdaQueryWrapper.in(ExpressDeliveryRecord::getOrderId, appUserOrder.getOrderId());
                expressDeliveryRecordService.remove(expressDeliveryRecordLambdaQueryWrapper);
                expressDeliveryRecordService.saveBatch(expressDeliveryRecordList);
                appUserOrder.setDeliveryTime(expressDeliveryRecordList.stream().map(ExpressDeliveryRecord::getFtime).min(Date::compareTo).get());
                if (subscribePushParamResp.getLastResult().getState().equals("3")) {
                    //快递完成
                    appUserOrder.setLogisticsStatus(3);
                    appUserOrder.setOrderStatus(3);
                    this.updateById(appUserOrder);
                    LambdaQueryWrapper<AppUserOrderDetails> appUserOrderDetailsLambdaQueryWrappera = new LambdaQueryWrapper();
                    appUserOrderDetailsLambdaQueryWrappera.eq(AppUserOrderDetails::getOrderId, appUserOrder.getOrderId());
                    List<AppUserOrderDetails> appUserOrderDetailsList = applicationUserOrderDetailsService.list(appUserOrderDetailsLambdaQueryWrappera);
                    if(appUserOrder.getPushStatus().equals(2)) {
                        String concatenatedDetails = appUserOrderDetailsList.stream()
                                .map(orderDetails -> {
                                    return "  #### 商品名称：" + orderDetails.getProName() + " ,数量：`" + orderDetails.getProVolume() + orderDetails.getProUnit() + "`,单价：" + orderDetails.getProPrice() / 100 + "元\\n";
                                }).collect(Collectors.joining(""));
                        WorkWechatSendMsgUtils.setBotMsg("# 收货通知\\n订单编号：" + appUserOrder.getOrderId() + "\\n物流公司`：" + appUserOrder.getCom() + "`\\n物流单号：`" + appUserOrder.getNum() + "`\\n订单总金额：`" + appUserOrder.getProTotal() / 100 + "`元\\n订单时间：" + DateUtil.formatDateTime(appUserOrder.getCreateTime()) + "\\n" +
                                "## 发货地址信息 \\n#### 收货人名称：" + appUserOrder.getAddName() + ",\\n #### 收货人电话：" + appUserOrder.getAddPhone() + ",\\n#### 收货人地址：" +
                                appUserOrder.getProvince() + appUserOrder.getCity() + appUserOrder.getCounty() + appUserOrder.getAddInfo() + appUserOrder.getCompanyName() +
                                "\\n> ## 发货商品信息\\n>" +
                                concatenatedDetails +
                                "`请关注快递信息动态`", "markdown", 1, 5, workWechatMsgInfoMapper, workWechatMsgContextMapper);
                        appUserOrder.setPushStatus(3);
                    }
                    this.updateById(appUserOrder);
                }
            });

            subscribeResp.setResult(Boolean.TRUE);
            subscribeResp.setMessage("成功");
            subscribeResp.setMessage("200");
        }
        return subscribeResp;
    }

}
